﻿/**
 * Slider.js
 */
$.Slider = $({
	__init : function (sets) {
		//if (!(sets&&sets.track&&sets.track.e&&sets.drager&&sets.drager.e) throw "$.Slider:Sets Wrong!";
		var $tracker = sets.$tracker, $dragger = sets.$dragger;
		var draggerWidth = $dragger.$('offsetWidth');
		var range = [0, $tracker.$('offsetWidth')];
		range[1] = range[1] - draggerWidth;
		var len = range[1] - range[0];
		var pos = $tracker.$('$$position');
		var _t = this;
		var onDrag = function (p) {
			if (sets.onChange) sets.onChange(_t.val());
		};
		new $.SDrag($dragger, null, {
			axis : 'H',
			cursor : 'pointer',
			rangeX : [range[0], len + range[0]],
			onDrag : onDrag
		});
		
		this.$draggerRange = function () {
			var l = parseInt($dragger.css('left'));
			return [l, l + draggerWidth];
		};
		$tracker.click(function(event){
			if ($(event,'element') == $dragger.e) return;
			var x = $(event, 'x') - pos[0] - Math.round(draggerWidth / 2);
			x = Math.max(0, x); x = Math.min(x, range[1]);
			_t.toPos(x);
		});
		this.effect = $.effect({
			duration : 0.5,
			startX : null,
			s : null,
			render : function (pos) {
				var x = this.startX + Math.floor(this.s * pos);
				$dragger.css('left:' + x + 'px');
			},
			onFinish : function () {
				if (sets.onChange) sets.onChange(_t.val());	
			}
		});
		this.sets = sets;
		this.$dragger = $dragger;
		this.range = range;
		this.len = len;
		this.draggerWidth = draggerWidth;
	},
	val : function () {
		var left = parseInt(this.$dragger.css('left'), 10);
		var per = left / this.len;
		if (!this.sets.range) return per;
		var range = this.sets.range;
		var val = range[0] + (range[1] - range[0]) * per;
		if (!this.sets.step) return val;
		return this.sets.step * Math.floor(val / this.sets.step);
	},
	toPos : function (pos, per) {
		var dr = this.$draggerRange(), range = this.range, len = this.len;
		var x = per ? (Math.floor(per * len) + range[0]) : pos, clickX = x + Math.round(this.draggerWidth/2);
		if (clickX < range[0] || clickX > range[1] + this.draggerWidth) return;
		if (per) return this.$dragger.css('left:' + x + 'px');
		this.effect.startX = dr[0];
		this.effect.s = x - dr[0];	
		$.Effect.add(this.effect);	
	}
});